/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package main;

import aso.upna.playlist.GenericIterator;
import aso.upna.playlist.GenericList;
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 * @author triki
 */
public class RegisterUsers {

    private ConcurrentHashMap users;
    private DirHandler dir;

    public RegisterUsers(DirHandler d)
    {
        users = new ConcurrentHashMap();
        dir = d;
    }

    public boolean registerUser(String user)
    {
        if(!users.contains(user))
        {
            users.put(user, user);
            return true;
        }
        return false;
    }

    public GenericList registerUser(GenericList l_users)
    {
        removeDisconnected(l_users);
        GenericList list = new GenericList();
        GenericIterator iter = l_users.getIterator();
        
        while(iter.hasNext())
        {
            String aux = (String)iter.current();
            if(registerUser(aux))
                list.addElement(aux);
            iter.next();
        }
        
        return list;
    }

    public void removeDisconnected(GenericList l)
    {
        Collection col = users.values();
        Iterator col_iter = col.iterator();
        GenericIterator g_iter = l.getIterator();
        boolean exists;
        String reg_user = null;
        String f_user = null;

        while(col_iter.hasNext())
        {
            reg_user = (String) col_iter.next();
            exists = false;

            g_iter = l.getIterator();
            while(g_iter.hasNext())
            {
                f_user = (String) g_iter.current();
               
                if(reg_user.equalsIgnoreCase(f_user))
                {
                    exists = true;
                    break;
                }
                
                g_iter.next();
            }
            if(!exists) //entonces el usuario se ha desconectado luego lo borramos de la hashtable
            {
                users.remove(reg_user);
                dir.deleteFile(reg_user,".bin");
            }
        }
    }

    public boolean isRegistered(String user)
    {
        return users.contains(user);
    }

    public void unregisterUser(String user)
    {
        users.remove(user);
    }
}
